<template>
  <div class="chat-container">
    <div class="chat-header">
      <h1>山与林 AI 聊天助手</h1>
      <div class="status-indicator" id="statusIndicator">{{ statusText }}</div>
    </div>
    
    <div class="chat-messages" ref="chatMessages" id="chatMessages">
      <div class="loading-message" v-if="!isModelLoaded" id="loadingMessage">
        正在初始化AI模型，请稍候...
      </div>
      
      <div 
        v-for="(message, index) in messages" 
        :key="index" 
        :class="['message', message.sender]"
      >
        <div class="message-avatar">
          {{ message.sender === 'user' ? '你' : 'AI' }}
        </div>
        <div class="message-content">
          {{ message.content }}
        </div>
      </div>
      
      <!-- 打字指示器 -->
      <div v-if="isTyping" class="message bot" id="typingIndicator">
        <div class="message-avatar">AI</div>
        <div class="typing-indicator">
          <div class="typing-dots">
            <div class="typing-dot"></div>
            <div class="typing-dot"></div>
            <div class="typing-dot"></div>
          </div>
        </div>
      </div>
    </div>
    
    <div class="chat-input-container">
      <form class="chat-input-form" @submit.prevent="handleSubmit" id="chatForm">
        <input 
          type="text" 
          class="chat-input" 
          v-model="messageInput"
          id="messageInput"
          placeholder="输入您的消息..." 
          :disabled="!isModelLoaded || isTyping"
          @keypress="handleKeypress"
        >
        <button 
          type="submit" 
          class="send-button" 
          id="sendButton"
          :disabled="!isModelLoaded || isTyping"
        >
          发送
        </button>
      </form>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Home',
  data() {
    return {
      messages: [],
      messageInput: '',
      isModelLoaded: false,
      isTyping: false,
      statusText: '模型已就绪 (🚀 GPU: NVIDIA GeForce GTX 1660 SUPER)，开始对话吧！',
      statusCheckInterval: null
    }
  },
  mounted() {
    this.init()
  },
  beforeUnmount() {
    if (this.statusCheckInterval) {
      clearInterval(this.statusCheckInterval)
    }
  },
  methods: {
    init() {
      this.checkModelStatus()
      this.statusCheckInterval = setInterval(() => this.checkModelStatus(), 2000)
    },
    
    async checkModelStatus() {
      try {
        const response = await fetch('http://192.168.1.119:5050/status')
        const data = await response.json()
        
        if (data.model_loaded && !this.isModelLoaded) {
          this.isModelLoaded = true
          
          // 显示设备信息
          let deviceInfo = ''
          if (data.device_info && data.device_info.device) {
            if (data.device_info.device === 'cuda') {
              deviceInfo = ` (🚀 GPU: ${data.device_info.gpu_name || 'CUDA'})`
            } else {
              deviceInfo = ' (💻 CPU)'
            }
          }
          
          this.statusText = `模型已就绪${deviceInfo}，开始对话吧！`
          
          // 添加欢迎消息，包含设备信息
          let welcomeMsg = '你好！我是山与林 AI助手，很高兴为您服务。'
          welcomeMsg += '\n\n请问有什么可以帮助您的吗？'
          
          this.addMessage('bot', welcomeMsg)
          
          clearInterval(this.statusCheckInterval)
        }
      } catch (error) {
        console.error('检查模型状态失败:', error)
      }
    },
    
    handleKeypress(e) {
      if (e.key === 'Enter' && !e.shiftKey) {
        e.preventDefault()
        this.handleSubmit()
      }
    },
    
    async handleSubmit() {
      const message = this.messageInput.trim()
      if (!message || this.isTyping) return
      
      this.addMessage('user', message)
      this.messageInput = ''
      this.setTyping(true)
      
      try {
        const response = await fetch('http://192.168.1.119:5050/chat', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ message: message })
        })
        
        const data = await response.json()
        
        setTimeout(() => {
          this.setTyping(false)
          this.addMessage('bot', data.response)
        }, 1000)
        
      } catch (error) {
        this.setTyping(false)
        this.addMessage('bot', '抱歉，发生了错误，请稍后重试。')
        console.error('发送消息失败:', error)
      }
    },
    
    addMessage(sender, content) {
      this.messages.push({
        sender,
        content
      })
      this.$nextTick(() => {
        this.scrollToBottom()
      })
    },
    
    setTyping(isTyping) {
      this.isTyping = isTyping
    },
    
    scrollToBottom() {
      if (this.$refs.chatMessages) {
        this.$refs.chatMessages.scrollTop = this.$refs.chatMessages.scrollHeight
      }
    }
  }
}
</script>

<style scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.chat-container {
  position: absolute;
  left: calc(80px + 2vw);
  top: 1vh;
  width: calc(100vw - 80px - 3vw);
  height: 96vh;
  background: white;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.chat-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 20px;
  text-align: center;
  position: relative;
}

.chat-header h1 {
  font-size: 24px;
  margin-bottom: 5px;
}

.status-indicator {
  font-size: 14px;
  opacity: 0.9;
}

.chat-messages {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background: #f8f9fa;
}

.message {
  margin-bottom: 15px;
  display: flex;
  align-items: flex-start;
}

.message.user {
  justify-content: flex-end;
}

.message-content {
  max-width: 70%;
  padding: 12px 16px;
  border-radius: 18px;
  word-wrap: break-word;
  line-height: 1.4;
}

.message.user .message-content {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-bottom-right-radius: 4px;
}

.message.bot .message-content {
  background: white;
  color: #333;
  border: 1px solid #e1e5e9;
  border-bottom-left-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.message-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  margin: 0 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  font-size: 14px;
}

.message.user .message-avatar {
  background: #667eea;
  color: white;
  order: 1;
}

.message.bot .message-avatar {
  background: #f1f3f4;
  color: #5f6368;
}

.chat-input-container {
  padding: 20px;
  background: white;
  border-top: 1px solid #e1e5e9;
}

.chat-input-form {
  display: flex;
  gap: 10px;
}

.chat-input {
  flex: 1;
  padding: 12px 16px;
  border: 2px solid #e1e5e9;
  border-radius: 25px;
  font-size: 16px;
  outline: none;
  transition: border-color 0.3s;
}

.chat-input:focus {
  border-color: #667eea;
}

.send-button {
  padding: 12px 24px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 25px;
  cursor: pointer;
  font-size: 16px;
  font-weight: 600;
  transition: transform 0.2s, box-shadow 0.2s;
}

.send-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.send-button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.typing-indicator {
  display: block;
  padding: 12px 16px;
  background: white;
  border: 1px solid #e1e5e9;
  border-radius: 18px;
  border-bottom-left-radius: 4px;
  max-width: 70%;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.typing-dots {
  display: flex;
  gap: 4px;
}

.typing-dot {
  width: 8px;
  height: 8px;
  background: #667eea;
  border-radius: 50%;
  animation: typing 1.4s infinite;
}

.typing-dot:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-dot:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0%, 60%, 100% {
    transform: translateY(0);
    opacity: 0.4;
  }
  30% {
    transform: translateY(-10px);
    opacity: 1;
  }
}

.loading-message {
  text-align: center;
  padding: 20px;
  color: #667eea;
  font-style: italic;
}

/* 滚动条样式 */
.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.chat-messages::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chat-container {
    width: 100%;
    height: 100vh;
  }

  .message-content {
    max-width: 85%;
  }

  .chat-header h1 {
    font-size: 20px;
  }
}
</style>